const request = require('../../utils/request');
const buildUrl = request.buildUrl || ((url) => url);
Page({
  data: {
    currentTab: 0,
    currentFilter: 'all',

    // 用户信息
    userInfo: {
      id: '',
      nickname: '',
      phone: '',
      avatarUrl: ''
    },

    // 信用分相关
    creditScore: 100,
    creditTrend: 'flat', // up, down, flat
    creditChange: 0,

    // 钱包
    walletBalance: 0,

    // 统计数据
    stats: {
      todayOrders: 0,
      completedOrders: 0,
      pendingOrders: 0,
      totalOrders: 0
    },

    // 订单数据
    orders: [],
    filteredOrders: [],
    totalAmount: 0
  },

  onLoad() {
    const app = getApp();
    console.log('🔍 检查登录状态:', {
      userId: app.globalData.userId,
      isLoggedIn: app.globalData.isLoggedIn
    });

    if (!app.globalData.userId) {
      wx.reLaunch({ url: '/pages/login/login' });
      return;
    }

    this.loadOrders();
  },

  onShow() {
    this.refreshData();
  },

  // 加载用户数据
  async loadUserData() {
    const app = getApp();
    const userId = app.globalData.userId;

    if (!userId) {
      wx.reLaunch({ url: '/pages/login/login' });
      return;
    }

    try {
      // 获取用户信息
      const userRes = await this.request({
        url: `/api/users/${userId}`,
        method: 'GET'
      });

      if (userRes.success && userRes.data) {
        const raw = userRes.data;
        const avatarPath = raw.avatar_url || raw.avatarUrl || '';
        const mappedUser = {
          id: raw.id,
          nickname: raw.nickname || '',
          phone: raw.phone || '',
          avatarUrl: avatarPath ? buildUrl(avatarPath) : ''
        };

        this.setData({
          userInfo: mappedUser
        });
      }

      // 获取信用分
      const creditRes = await this.request({
        url: `/api/users/order-users/credit/${userId}`,
        method: 'GET'
      });

      if (creditRes.success) {
        this.setData({
          creditScore: creditRes.data.score || 100,
          creditTrend: creditRes.data.trend || 'flat',
          creditChange: creditRes.data.change || 0
        });
      }

      // 获取钱包余额
      const walletRes = await this.request({
        url: `/api/payments/balance/${userId}`,
        method: 'GET'
      });

      if (walletRes.success) {
        this.setData({
          walletBalance: walletRes.data.balance || 0
        });
      }

      // 获取统计数据
      const statsRes = await this.request({
        url: `/api/orders/stats/${userId}`,
        method: 'GET'
      });

      if (statsRes.success) {
        this.setData({
          stats: statsRes.data
        });
      }

    } catch (error) {
      console.error('加载用户数据失败:', error);
      wx.showToast({ title: '数据加载失败', icon: 'none' });
    }
  },

  // 加载订单数据
  // orderUser.js 中的 loadOrders 方法
  loadOrders() {
    const that = this;
    const userId = wx.getStorageSync('userId');

    console.log('📦 获取用户订单，用户ID:', userId);

    request({
      url: `/api/orders/user/${userId}`,
      method: 'GET'
    }).then(res => {
      console.log('📦 订单API响应:', res);

      // 检查响应结构
      if (res.success && res.data) {
        let orders = [];

        // 处理不同的数据结构
        if (Array.isArray(res.data)) {
          // 情况1: data 直接是数组
          orders = res.data;
        } else if (res.data.orders && Array.isArray(res.data.orders)) {
          // 情况2: data 包含 orders 属性
          orders = res.data.orders;
        } else if (Array.isArray(res.data.list)) {
          // 情况3: data 包含 list 属性
          orders = res.data.list;
        }

        console.log('✅ 解析后的订单数据:', orders);

        const enhancedOrders = orders.map(order => {
          // 处理备注中的期望时间段
          let rawNote = order.note || '';
          let expectTimeRange = '';
          if (rawNote) {
            const match = rawNote.match(/期望时间段[:：]\s*(.+)$/);
            if (match) {
              expectTimeRange = match[1];
              rawNote = rawNote.replace(/\s*期望时间段[:：].*$/, '');
            }
          }

          return {
            ...order,
            // 字段归一化，方便 WXML 使用
            expressCompany: order.expressCompany || order.express_company || '',
            pickupLocation: order.pickupLocation || order.pickup_location || '',
            deliveryAddress: order.deliveryAddress || order.delivery_address || '',
            pickupCode: order.pickupCode || order.pickup_code || '',
            deliveryTime: order.deliveryTime || order.delivery_time || '',
            note: rawNote,
            expectTimeRange,
            expressType: order.expressType || order.express_type || '',
            finalFee: order.finalFee || order.final_fee || order.suggested_fee || '',
            statusText: that.getStatusText(order.status),
            createdAt: that.formatTime(order.created_at || order.createdAt)
          };
        });

        that.setData({
          orders: enhancedOrders,
          filteredOrders: that.filterOrders(enhancedOrders, that.data.currentFilter),
          loading: false
        });
        that.calculateTotalAmount();
      } else {
        console.error('❌ 加载订单失败:', res.message || '未知错误');
        that.setData({
          orders: [],
          filteredOrders: [],
          loading: false
        });
      }
    }).catch(err => {
      console.error('❌ 请求订单失败:', err);
      that.setData({
        orders: [],
        filteredOrders: that.filterOrders([], 'pending'), // Ensure filteredOrders is populated with status text and formatted time
        loading: false
      });
    });
  },

  // 检查手机号验证状态
  // 切换标签页
  switchTab(e) {
    const tab = parseInt(e.currentTarget.dataset.tab);
    this.setData({ currentTab: tab });

    if (tab === 1) {
      this.loadOrders();
    }
  },

  // 设置订单筛选
  setFilter(e) {
    const filter = e.currentTarget.dataset.filter;
    const filteredOrders = this.filterOrders(this.data.orders, filter);

    this.setData({
      currentFilter: filter,
      filteredOrders: filteredOrders
    });

    this.calculateTotalAmount();
  },

  // 过滤订单
  filterOrders(orders, filter) {
    if (filter === 'all') return orders;

    const statusMap = {
      'pending': [1],        // 待接单
      'progress': [2, 3, 4], // 进行中 (已接单, 已取件, 送达中)
      'completed': [5]       // 已完成
    };

    return orders.filter(order =>
      statusMap[filter] && statusMap[filter].includes(order.status)
    );
  },

  // 计算总金额
  calculateTotalAmount() {
    const total = this.data.filteredOrders.reduce((sum, order) => {
      return sum + (parseFloat(order.finalFee) || 0);
    }, 0);

    this.setData({ totalAmount: total.toFixed(2) });
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      1: '待接单',
      2: '已接单',
      3: '已取件',
      4: '送达中',
      5: '已完成',
      6: '已取消'
    };
    return statusMap[status] || '未知状态';
  },

  // 格式化时间
  formatTime(timestamp) {
    if (!timestamp) return '';
    const date = new Date(timestamp);
    const now = new Date();
    const diff = now - date;
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));

    if (days === 0) {
      return `今天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    } else if (days === 1) {
      return `昨天 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    } else {
      return `${date.getMonth() + 1}-${date.getDate()} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    }
  },

  // 跳转到发布订单页
  goToCreateOrder() {
    wx.navigateTo({ url: '/pages/createOrder/createOrder' });
  },

  // 使用模板
  useTemplate(e) {
    const type = e.currentTarget.dataset.type;
    const templates = {
      small: {
        packageSize: 'S',
        packageWeight: 0.5,
        expressType: '文件'
      },
      medium: {
        packageSize: 'M',
        packageWeight: 2.0,
        expressType: '日常用品'
      },
      urgent: {
        isUrgent: true,
        expectedTime: '30分钟'
      }
    };

    const template = templates[type];
    if (template) {
      wx.setStorageSync('orderTemplate', template);
      this.goToCreateOrder();
    }
  },

  // 查看订单详情
  viewOrderDetail(e) {
    const orderId = e.currentTarget.dataset.orderId;
    wx.navigateTo({
      url: `/pages/orderDetail/orderDetail?orderId=${orderId}&role=order_user`
    });
  },

  // 取消订单
  async cancelOrder(e) {
    const orderId = e.currentTarget.dataset.orderId;

    wx.showModal({
      title: '确认取消',
      content: '取消订单可能会影响您的信用分，确定要取消吗？',
      confirmColor: '#ff4d4f',
      success: async (res) => {
        if (res.confirm) {
          try {
            const result = await this.request({
              url: `/api/orders/${orderId}/cancel`,
              method: 'POST'
            });

            if (result.success) {
              wx.showToast({ title: '订单已取消' });
              this.loadOrders();
              this.loadUserData(); // 刷新信用分
            } else {
              wx.showToast({ title: result.message || '取消失败', icon: 'none' });
            }
          } catch (error) {
            wx.showToast({ title: '取消失败', icon: 'none' });
          }
        }
      }
    });
  },

  // 确认收货
  async confirmDelivery(e) {
    const orderId = e.currentTarget.dataset.orderId;
    const app = getApp();
    const userId = app.globalData.userId || wx.getStorageSync('userId');

    if (!userId) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      wx.reLaunch({ url: '/pages/login/login' });
      return;
    }

    const order = this.data.orders.find(o => String(o.id) === String(orderId));
    if (!order) {
      wx.showToast({ title: '订单信息异常', icon: 'none' });
      return;
    }

    const amount = Number(order.finalFee || order.final_fee || order.suggested_fee || order.amount || 0);
    if (!amount || amount <= 0) {
      wx.showToast({ title: '订单金额异常', icon: 'none' });
      return;
    }

    wx.showModal({
      title: '确认送达并支付',
      content: `请确认已收到包裹，将支付 ¥${amount.toFixed(2)}。`,
      success: (res) => {
        if (!res.confirm) return;

        const openid = wx.getStorageSync('wechat_openid') || null;

        wx.showLoading({ title: '支付中...' });

        wx.request({
          url: buildUrl('/api/payments/create'),
          method: 'POST',
          header: {
            'Content-Type': 'application/json'
          },
          data: {
            order_id: orderId,
            user_id: userId,
            amount: amount,
            payment_method: 'wechat',
            discount: 0,
            openid: openid
          },
          success: (res2) => {
            wx.hideLoading();
            const data = res2.data || {};
            if (data && data.success && data.data) {
              const payData = data.data;

              // 开发环境模拟支付：后端已直接标记订单完成
              if (payData.paymentType === 'mock' || !payData.paymentType) {
                wx.showToast({ title: '支付成功（测试环境）', icon: 'success' });
                setTimeout(() => {
                  wx.navigateTo({ url: `/pages/rating/rating?orderId=${orderId}` });
                }, 1000);
                return;
              }

              if (payData.paymentType === 'wechat_jsapi' && payData.params) {
                const p = payData.params;
                wx.requestPayment({
                  timeStamp: String(p.timeStamp || p.timestamp || ''),
                  nonceStr: p.nonceStr,
                  package: p.package,
                  signType: p.signType || 'MD5',
                  paySign: p.paySign,
                  success: () => {
                    wx.showToast({ title: '支付成功', icon: 'success' });
                    setTimeout(() => {
                      wx.navigateTo({ url: `/pages/rating/rating?orderId=${orderId}` });
                    }, 1000);
                  },
                  fail: (err) => {
                    console.error('微信支付失败:', err);
                    wx.showToast({ title: '支付已取消或失败', icon: 'none' });
                  }
                });
              } else {
                wx.showToast({ title: '暂不支持该支付方式', icon: 'none' });
              }
            } else {
              wx.showToast({ title: data.message || '支付失败', icon: 'none' });
            }
          },
          fail: (err) => {
            wx.hideLoading();
            console.error('💥 支付请求失败:', err);
            wx.showToast({ title: '支付失败，请稍后重试', icon: 'none' });
          }
        });
      }
    });
  },

  // 跳转到评价
  goToRating(e) {
    const orderId = e.currentTarget.dataset.orderId;
    wx.navigateTo({
      url: `/pages/rating/rating?orderId=${orderId}`
    });
  },

  // 编辑个人信息
  editProfile() {
    wx.navigateTo({ url: '/pages/profile/editProfile' });
  },

  // 跳转到钱包
  goToWallet() {
    wx.navigateTo({ url: '/pages/profile/wallet' });
  },

  // 查看订单统计
  viewOrderHistory() {
    wx.navigateTo({ url: '/pages/profile/orderHistory' });
  },

  // 显示系统设置列表
  showSettings() {
    wx.navigateTo({ url: '/pages/profile/settingsCenter' });
  },

  // 显示帮助（跳转到帮助中心使用指南）
  showHelp() {
    // 下单者的帮助上下文
    wx.navigateTo({ url: '/pages/profile/helpCenter?context=order_user' });
  },

  // 显示信用规则
  showCreditRules() {
    wx.showModal({
      title: '信用分规则',
      content: `• 初始信用值：100分
• 期望送达时间前2小时内取消订单：-1分
• 24小时内未完成支付：-2分
• 及时完成订单：+1分
• 获得好评：+2分`,
      showCancel: false,
      confirmText: '知道了'
    });
  },

  // 意见反馈
  showFeedback() {
    wx.navigateTo({ url: '/pages/profile/feedback' });
  },

  // 退出登录
  logout() {
    wx.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      confirmColor: '#ff4d4f',
      success: (res) => {
        if (res.confirm) {
          wx.clearStorageSync();
          getApp().globalData.userId = null;
          getApp().globalData.userRole = null;
          getApp().globalData.isLoggedIn = false;
          wx.reLaunch({ url: '/pages/login/login' });
        }
      }
    });
  },

  // 刷新数据
  refreshData() {
    this.loadUserData();
    if (this.data.currentTab === 1) {
      this.loadOrders();
    }
  },

  // 网络请求封装
  request(options) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: buildUrl(options.url || ''),
        method: options.method || 'GET',
        data: options.data,
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${wx.getStorageSync('token')}`
        },
        success: (res) => {
          resolve(res.data);
        },
        fail: (err) => {
          reject(err);
        }
      });
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.refreshData();
    setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 1000);
  }
});